package com.lc.app.androidfirst.userdefine.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lc.app.androidfirst.R;
import com.lc.app.androidfirst.userdefine.Constants;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.util.concurrent.RecursiveAction;

public class ContentProviderActivity extends AppCompatActivity {
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private static final String KEY_SP = "mytest";


    private Button btnTestButtonRead;
    private Button btnTestButtonWrite;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_content_provider);
        btnTestButtonRead = (Button) findViewById(R.id.testButtonRead);
        btnTestButtonWrite = (Button)findViewById(R.id.testButtonWrite);
        final EditText editText = (EditText) findViewById(R.id.testWrite);
        final TextView readText = (TextView) findViewById(R.id.testShow);
        final TextView titleText = (TextView) findViewById(R.id.testTitle);

        Intent intent = getIntent();
        String flag = (String) intent.getExtras().get(Constants.KEY_CONTENT_PROVIDER);

        if(flag.equals(Constants.READ_WRITE_SHARED_PREFERENCES)){
            titleText.setText("Shared Preferences");
            sharedPreferences = getSharedPreferences(KEY_SP, Context.MODE_PRIVATE);
            editor = sharedPreferences.edit();


            // init show sp
            if(sharedPreferences.contains(KEY_SP)){
                String value =  sharedPreferences.getString(KEY_SP,"Default Value.");
                readText.setText(value);
            }
            btnTestButtonRead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(sharedPreferences.contains(KEY_SP)){
                        String value =  sharedPreferences.getString(KEY_SP,"Default Value.");
                        readText.setText(value);
                    }else{
                        Toast.makeText(getApplicationContext(),"No SharedPreferences.",Toast.LENGTH_SHORT).show();
                    }
                }
            });

            btnTestButtonWrite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(editText.getEditableText() != null && !"".equals(editText.getEditableText().toString().trim())){
                        editor.putString(KEY_SP,editText.getEditableText().toString());
                        editor.commit();
                        Toast.makeText(getApplicationContext(),"Save Shared Preferences Success",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"Please Input Value",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }else if(flag.equals(Constants.READ_WRITE_FILE)){
            titleText.setText("File read and write");
            RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_content_provider);
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp1.addRule(RelativeLayout.BELOW, R.id.testButtonWrite);
            Button btnAppendWrite = new Button(this);
            btnAppendWrite.setText("Append");
            layout.addView(btnAppendWrite,lp1);

            String value = read();
            if(value != null){
                readText.setText(value);
            }
            btnTestButtonRead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String value = read();
                    if(value != null){
                        readText.setText(value);
                    }
                }
            });

            btnTestButtonWrite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(editText != null && !editText.getText().toString().equals("") ){
                        String content = editText.getText().toString();
                        write(content,false);
                        editText.setText("");
                        Toast.makeText(getApplicationContext(),"Write to file successfully.",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"Please input value",Toast.LENGTH_SHORT).show();
                    }
                }
            });

            btnAppendWrite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(editText != null && !editText.getText().toString().equals("") ){
                        String content = editText.getText().toString();
                        write(content,true);
                        editText.setText("");
                        Toast.makeText(getApplicationContext(),"Write to file successfully.",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"Please input value",Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }else if(flag.equals(Constants.READ_WRITE_SDCARD)){
            titleText.setText("SD Card read and write");
            RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_content_provider);
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp1.addRule(RelativeLayout.BELOW, R.id.testButtonWrite);
            Button btnAppendWrite = new Button(this);
            btnAppendWrite.setText("Append");
            layout.addView(btnAppendWrite,lp1);

            String value = readSDCard();
            if(value != null){
                readText.setText(value);
            }
            btnTestButtonRead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String value = readSDCard();
                    if(value != null){
                        readText.setText(value);
                    }
                }
            });

            btnTestButtonWrite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(editText != null && !editText.getText().toString().equals("") ){
                        String content = editText.getText().toString();
                        writeSDCard(content,false);
                        editText.setText("");
                        Toast.makeText(getApplicationContext(),"Write to sd card successfully.",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"Please input value",Toast.LENGTH_SHORT).show();
                    }
                }
            });

            btnAppendWrite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(editText != null && !editText.getText().toString().equals("") ){
                        String content = editText.getText().toString();
                        writeSDCard(content,true);
                        editText.setText("");
                        Toast.makeText(getApplicationContext(),"Write to sd card successfully.",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"Please input value",Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

    }


    private String read(){
        try {
            StringBuffer sb = new StringBuffer();
            FileInputStream in = openFileInput(Constants.FILE_NAME_CONTENT_PROVIDER_FILE_NAME);
            byte[] buff = new byte[512];
            int length = 0;
            while( (length = in.read(buff)) > 0){
                sb.append(new String(buff,0,length));
            }
            in.close();
            return sb.toString();
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(),"File not exist.",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e1){
            e1.printStackTrace();
        }

        return null;
    }

    private void write(String content,boolean isAppend){
        FileOutputStream out = null;
        try {
            if(isAppend){
                out = openFileOutput(Constants.FILE_NAME_CONTENT_PROVIDER_FILE_NAME,MODE_APPEND);
            }else{
                out = openFileOutput(Constants.FILE_NAME_CONTENT_PROVIDER_FILE_NAME,MODE_PRIVATE);
            }
            PrintStream ps = new PrintStream(out);
            ps.print(content);
            ps.close();
            ps.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private String readSDCard(){
        try {
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File sdCardDir = Environment.getExternalStorageDirectory();
                FileInputStream fin = new FileInputStream(sdCardDir.getCanonicalPath()+Constants.FILE_NAME_READ_WRITE_SD_FILE);
                BufferedReader br = new BufferedReader(new InputStreamReader(fin));
                StringBuffer sb = new StringBuffer();
                String line = null;
                while(br.readLine() != null){
                    sb.append(line);
                }
                return sb.toString();
            }else{
                Toast.makeText(getApplicationContext(),"You do not have a sd card or do not have priviledge to use it.",Toast.LENGTH_SHORT).show();
            }
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(),"File not exist.",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e1){
            e1.printStackTrace();
        }

        return null;
    }

    private void writeSDCard(String content,boolean isAppend){

        try {
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File sdCardDir = Environment.getExternalStorageDirectory();
                File targetFile = new File(sdCardDir.getCanonicalPath()+Constants.FILE_NAME_READ_WRITE_SD_FILE);
                RandomAccessFile raf = new RandomAccessFile(targetFile,"rw");
                raf.seek(targetFile.length());
                raf.write(content.getBytes());
                raf.close();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
